<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="文章管理" prop="title">
            <el-input v-model="form.title" placeholder="输入文章标题" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="danger" @click="onSubmit">发布文章</el-button>
            <el-button @click="onDraft">保存草稿</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <mavon-editor
        class="md"
        v-model="form.content"
        :subfield="false"
        :toolbars-flag="true"
        :box-shadoww="true"
        :editable="true"
        :scroll-style="false"
        :ishljs="true"
        ref="md"
        @imgAdd="$imgAdd"
        @imgDel="$imgDel"
      />
    </el-form>
    <el-dialog title="发布文章" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="文章标签:" prop="keyword">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            effect="dark"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
        </el-form-item>
        <el-form-item label="分类专栏:" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.categories"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章类型:" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="原创" value="原创" />
            <el-option label="转载" value="转载" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布形式:" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">公开</el-radio>
            <el-radio :label="1">私密</el-radio>
            <el-radio :label="2">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button @click="onDraft()">
          保存草稿
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { detailArticle, saveArticle, updateArticle, uploadImage } from '@/api/article'
import { getList } from '@/api/column'
import { readTime, wordTotal } from '@/utils/wordcount'

export default {
  data() {
    const tagsKey = (rule, value, callback) => {
      if (this.dynamicTags.length === 0) {
        callback(new Error('请添加文章标签'))
      } else {
        callback()
      }
    }
    return {
      title: '',
      content: '',
      form: {
        hid: '',
        title: '',
        content: '',
        summary: '',
        categoryId: 0,
        type: '',
        keyword: '',
        status: '',
        images: '',
        wordTotal: '',
        readTime: ''
      },
      rules: {
        keyword: [{ validator: tagsKey, trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        title: [{ required: true, message: '文章标题不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        status: [{ required: true, message: '请选择发布方式', trigger: 'change' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dynamicTags: [],
      categories: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  mounted() {
    // 如果原始md字符串中存在曾上传的图片， 则需要将对应<img>中的src替换为base64
    this.$nextTick(() => {
      // $vm.$imgUpdateByUrl 详情见本页末尾
      this.$refs.md.$imgUpdateByUrl(0, '')
    })
  },
  watch: {
    $route() {

    },
    dialogStatus() {
      if (this.dialogStatus === 'update') {
        const id = this.$route.query.id
        if (new RegExp('\\w{8}').test(id)) {
          this.fetchData(id)
        }
      }
    }
  },
  created() {
    const id = this.$route.query.id
    if (new RegExp('\\w{8}').test(id) && id !== undefined) {
      this.dialogStatus = 'update'
      this.fetchData(id)
    } else {
      this.dialogStatus = 'create'
    }
  },
  methods: {
    $imgAdd(pos, $file) {
      // 将图片上传到服务器.
      const formData = new FormData()
      formData.append('file', $file)
      uploadImage(formData).then(response => {
        if (response.code === 20000) {
          this.$refs.md.$img2Url(pos, response.payload)
        }
      })
    },
    $imgDel() {

    },
    resetTemp() {
      this.form.type = '原创'
      this.form.categoryId = ''
      this.form.keyword = ''
      this.form.status = 0
      this.dynamicTags = []
    },
    onSubmit() {
      if (this.dialogStatus === 'create') {
        this.resetTemp()
      }
      const id = this.$route.query.id
      if (new RegExp('\\w{8}').test(id) && id !== undefined) {
        this.dialogStatus = 'update'
      }
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message.error('文章标题不能为空')
        } else {
          this.dialogFormVisible = true
        }
      })
      getList().then(response => {
        this.categories = response.payload.list
      })
    },
    onDraft() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message.error('文章标题不能为空')
        } else {
          this.form.status = 2
          saveArticle(this.form).then(response => {
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '保存失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.keyword = this.dynamicTags.join(',')
          this.form.wordTotal = wordTotal(this.form.content)
          this.form.readTime = readTime(this.form.content)
          saveArticle(this.form).then(response => {
            this.dialogFormVisible = false
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.$router.push({ path: '/document/console/article' })
            } else {
              this.$notify({
                title: '失败',
                message: '发布失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.keyword = this.dynamicTags.join(',')
          this.form.wordTotal = wordTotal(this.form.content)
          this.form.readTime = readTime(this.form.content)
          updateArticle(this.form).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.$router.push({ path: '/document/console/article' })
          })
        }
      })
    },
    fetchData(id) {
      if (new RegExp('\\w{8}').test(id) && id !== undefined) {
        detailArticle(id).then(response => {
          if (response.code === 20000) {
            this.form = response.payload
            this.form.content = response.payload.content
            this.form.publish = response.payload.publish
            this.dynamicTags = response.payload.keyword.split(',')
          }
        })
      }
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
  .md {
    width: 100%;
    height: 100%;
    min-height: 600px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

